package com.xxjqr.rbac.auth;


import cn.hutool.core.convert.Convert;
import com.xxjqr.rbac.mapper.TbRoleMenuRelMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.stereotype.Service;
import org.springframework.security.access.SecurityConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class DynamicSecurityService {

    private final TbRoleMenuRelMapper roleMenuRelMapper;

    Map<String, List<ConfigAttribute>> loadDataSource() {
        List<Map<String, Object>> urlRoleMaps = roleMenuRelMapper.getUrlRoleMap();
        Map<String, List<ConfigAttribute>> configAttributeMap = new HashMap<>();

        for (Map<String, Object> urlRoleMap : urlRoleMaps) {

            String bindUrl = urlRoleMap.get("bindUrl").toString();
            Object roleIdsObj = urlRoleMap.get("roleCodes");
            if (roleIdsObj != null) {
                List<String> roleCodes = Convert.toList(String.class, roleIdsObj);
                //创建string数组来转角色编码，然后转成List<ConfigAttribute>
                String[] configAttributes = new String[roleCodes.size()];
                for (int i = 0; i < roleCodes.size(); i++) {
                    configAttributes[i] = roleCodes.get(i);
                }
                configAttributeMap.put(bindUrl, SecurityConfig.createList(configAttributes));
            }
        }
        return configAttributeMap;
    }
}
